<template>
  <div class="admin">
    <el-button type="success" style="float: left;margin-bottom: 10px" plain @click="addUser">新增用户</el-button>
    <el-table
        v-loading="loading"
        :data="message"
        :row-class-name="tableRowClassName">
      <el-table-column
          align="center"
          prop="nickname"
          label="昵称"
          width="180">
      </el-table-column>
      <el-table-column
          align="center"
          prop="phone"
          label="手机"
          width="180">
      </el-table-column>
      <el-table-column
          align="center"
          prop="password"
          label="密码"
          width="300">
      </el-table-column>
      <el-table-column
          align="center"
          prop="creatDate"
          label="创建时间"
          width="180">
      </el-table-column>
      <el-table-column
          align="center"
          fixed="right"
          label="操作"
          width="100">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope.row)" type="text" size="small">删除</el-button>
          <el-button @click="handleClickUpdate(scope.row)" type="text" size="small">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        small
        layout="prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="allInfo.pageNum"
        :page-size="allInfo.pageSize"
        :total="allInfo.total">
    </el-pagination>

    <el-dialog
        title="新增用户"
        :visible.sync="centerDialogVisible"
        width="30%"
        center>

      <el-card :xl="6" :md="8" :sm="12" :xs="22" class="box-card cardAdmin">
        <p class="login-welcome">&nbsp;&nbsp;欢迎注册！</p>
        <div style="margin-top: 10px"></div>
        <el-avatar :src="changeimg" style="cursor: pointer;margin-left: 50%;transform: translateX(-50%);" title="点击修改图片"
                   @click.native.prevent="getimg"></el-avatar>
        <input type="file" id="imgup" ref="inputer" accept="image/*" @change="upload_photo"
               style="display: none;"/>
        <div style="margin-top: 10px"></div>
        <el-form status-icon autocomplete="off">
          <el-form-item>
            <el-input
                prefix-icon="el-icon-user"
                type="text"
                placeholder="昵称"
                v-model="formCustom.nickname"
                autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
                style="width:100%"
                prefix-icon="el-icon-phone"
                type="text"
                placeholder="手机号"
                v-model="formCustom.phone"
                autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
                prefix-icon="el-icon-lock"
                type="password"
                placeholder="密码"
                v-model="formCustom.password"
                autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
                prefix-icon="el-icon-lock"
                type="password"
                placeholder="确认密码"
                v-model="formCustom.checkPass"
                autocomplete="off"
            ></el-input>
          </el-form-item>
          <div class="login-btn">
            <el-button v-loading="loading" class="btnAdmin" @click="changw">注册</el-button>
          </div>
        </el-form>
      </el-card>
      <span slot="footer" class="dialog-footer">
      </span>
    </el-dialog>

    <el-dialog
        title="修改信息"
        :visible.sync="centerDialogVisibleUpdate"
        width="30%"
        center>

      <el-card :xl="6" :md="8" :sm="12" :xs="22" class="box-card cardAdmin">
        <p class="login-welcome">&nbsp;&nbsp;欢迎修改！</p>
        <div style="margin-top: 10px"></div>
        <el-avatar :src="changeimgupdate" style="cursor: pointer;margin-left: 50%;transform: translateX(-50%);"
                   title="点击修改图片"
                   @click.native.prevent="getimg"></el-avatar>
        <input type="file" id="imgupDate" ref="inputer" accept="image/*" @change="upload_photo"
               style="display: none;"/>
        <div style="margin-top: 10px"></div>
        <el-form status-icon autocomplete="off">
          <el-form-item>
            <el-input
                prefix-icon="el-icon-user"
                type="text"
                placeholder="昵称"
                v-model="updateData.nickname"
                autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
                style="width:100%"
                prefix-icon="el-icon-phone"
                type="text"
                placeholder="手机号"
                v-model="updateData.phone"
                autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
                prefix-icon="el-icon-lock"
                type="password"
                placeholder="密码"
                v-model="updateData.password"
                autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
                prefix-icon="el-icon-lock"
                type="password"
                placeholder="确认密码"
                v-model="updateData.checkPass"
                autocomplete="off"
            ></el-input>
          </el-form-item>
          <div class="login-btn">
            <el-button v-loading="loading" class="btnAdmin" @click="changwe">更改</el-button>
          </div>
        </el-form>
      </el-card>

      <span slot="footer" class="dialog-footer">
      </span>
    </el-dialog>

  </div>
</template>

<script>


export default {
  name: "Admin",
  data: function () {
    return {
      allInfo: {},
      message: [],
      page: {
        pageNum: 1,
        pageSize: 5
      },
      loading: true,
      centerDialogVisible: false,
      formCustom: {
        nickname: "",
        password: "",
        checkPass: "",
        phone: "",
        headPortraitId: ""
      },
      changeimg: require("../assets/icon-注册头像.png"),
      changeimgupdate: null,
      formData: null,
      centerDialogVisibleUpdate: false,
      updateData: {},
      newOrUpdate: null
    }
  },
  mounted() {
    this.getPageInfo()
  },
  methods: {
    changwe() {
      if (this.updateData.phone == "" || this.updateData.nickname == "" || this.updateData.password == "" || this.updateData.checkPass == "") {
        this.$message.error("请输入全部信息！！")
        return
      }
      if (!this.phoneFun(this.updateData.phone)) {
        this.$message.error("请输入正确手机号！！")
        return
      }
      if (this.updateData.password != this.updateData.checkPass) {
        this.$message.error("两次密码输入不一致！！")
        return
      }
      if (this.formData == null) {
        this.update("")
      }else {
        this.$http({
          method: "post",
          url: "/login/uploadImg",
          headers: {
            'Content-Type': 'multipart/form-data',
          },
          data: this.formData
        }).then(data => {
          console.log(data)
          if (data.code == 200) {
            this.update(data.data)
          }
        })
      }
    },
    update(headPortraitId) {
      if (this.updateData.phone == "" || this.updateData.nickname == "" || this.updateData.password == "" || this.updateData.checkPass == "") {
        this.$message.error("请输入全部信息！！")
        return
      }
      if (!this.phoneFun(this.updateData.phone)) {
        this.$message.error("请输入正确手机号！！")
        return
      }
      if (this.updateData.password != this.updateData.checkPass) {
        this.$message.error("两次密码输入不一致！！")
        return
      }
      if(headPortraitId!=""){
        console.log("youtoux")
        this.updateData.headPortraitId = headPortraitId
      }
      this.$http.put("/admin/updateUser", this.updateData).then(async data => {
        if (data.code == 400) {
          this.$message.error(data.message)
          this.changeimg = require("../assets/icon-注册头像.png")
          this.formCustom = {
            nickname: "",
            password: "",
            checkPass: "",
            phone: "",
            headPortraitId: ""
          }
        } else {
          this.$message.success("修改成功！")
          this.centerDialogVisibleUpdate = false
          this.getPageInfo()
        }
      })
    },
    async handleClickUpdate(row) {
      this.newOrUpdate = "update"
      this.centerDialogVisibleUpdate = true
      await this.$http.get("/admin/getUserInfoById/" + row.id).then(async data => {
        let res = data.data
        await this.getimgInfo(res.headPortraitId).then(data => {
          this.changeimgupdate = data
          res.password = ""
        })
        this.updateData = res
      })
    },
    handleClick(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete("/admin/deleteUser/" + row.id).then(data => {
          if (data.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getPageInfo()
          } else {
            this.$message.error(data.message)
            this.getPageInfo()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    addUser() {
      this.newOrUpdate = "new"
      this.centerDialogVisible = true
    },
    async changw() {
      if (this.formCustom.phone == "" || this.formCustom.nickname == "" || this.formCustom.password == "" || this.formCustom.checkPass == "") {
        this.$message.error("请输入全部信息！！")
        return
      }
      if (!this.phoneFun(this.formCustom.phone)) {
        this.$message.error("请输入正确手机号！！")
        return
      }
      if (this.formCustom.password != this.formCustom.checkPass) {
        this.$message.error("两次密码输入不一致！！")
        return
      }
      if (this.formData == null) {
        this.$message.error("请设置头像！！")
        return
      }
      this.$http({
        method: "post",
        url: "/login/uploadImg",
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        data: this.formData
      }).then(data => {
        //console.log(data)
        if (data.code == 200) {
          this.login(data.data)
        }
      })
    },
    upload_photo() {
      let file;
      if (this.newOrUpdate == "new") {
        file = document.getElementById('imgup')
      } else {
        file = document.getElementById('imgupDate')
      }
      const fileObj = file.files[0];
      const windowURL = window.URL || window.webkitURL;
      if (file && fileObj) {
        const dataURl = windowURL.createObjectURL(fileObj);
        if (this.newOrUpdate == "new") {
          this.changeimg = dataURl;
        } else {
          this.changeimgupdate = dataURl;
        }

        let formData = new FormData();
        formData.append('file', fileObj);
        this.formData = formData;
      }
    },
    getimg() {
      if (this.newOrUpdate == "new") {
        document.getElementById("imgup").click();
      } else {
        document.getElementById("imgupDate").click();
      }
    },
    phoneFun(phones) {
      var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      if (!myreg.test(phones)) {
        return false;
      } else {
        return true;
      }
    },
    login(headPortraitId) {
      if (this.formCustom.phone == "" || this.formCustom.nickname == "" || this.formCustom.password == "" || this.formCustom.checkPass == "") {
        this.$message.error("请输入全部信息！！")
        return
      }
      if (!this.phoneFun(this.formCustom.phone)) {
        this.$message.error("请输入正确手机号！！")
        return
      }
      if (this.formCustom.password != this.formCustom.checkPass) {
        this.$message.error("两次密码输入不一致！！")
        return
      }
      if (this.formData == null) {
        this.$message.error("请设置头像！！")
        return
      }
      this.formCustom.headPortraitId = headPortraitId
      //console.log(this.formCustom)
      this.$http.post("/admin/register", this.formCustom).then(async data => {
        if (data.code == 400) {
          this.$message.error(data.message)
          this.changeimg = require("../assets/icon-注册头像.png")
          this.formCustom = {
            nickname: "",
            password: "",
            checkPass: "",
            phone: "",
            headPortraitId: ""
          }
        } else {
          this.changeimg = require("../assets/icon-注册头像.png")
          this.formCustom = {
            nickname: "",
            password: "",
            checkPass: "",
            phone: "",
            headPortraitId: ""
          }
          this.$message.success("注册成功！")
          this.centerDialogVisible = false
          this.getPageInfo()
        }
      })
    },
    getimgInfo(id) {
      return new Promise(resolve => {
        this.$http({
          url: "/file/img/" + id,
          method: "get",
          responseType: "arraybuffer",
        }).then(res => {
          let bytes = new Uint8Array(res);
          let storeData = "";
          let len = bytes.byteLength;
          for (let i = 0; i < len; i++) {
            storeData += String.fromCharCode(bytes[i]);
          }
          let database = "data:image/png;base64," + window.btoa(storeData);
          resolve(database);
        });
      })
    },
    getPageInfo() {
      this.$http.post("/admin/pageGetUserInfo", this.page).then(data => {
        let res = data.data.list
        for (let i = 0; i < res.length; i++) {
          res[i].password = '已用md5加密'

        }
        this.message = res
        this.allInfo = data.data
      })
      this.loading = false
    },
    // 监听页数变化
    handleSizeChange(pageSie) {
      this.page.pageSize = pageSie
      this.getPageInfo()
    },
    // 监听当前页变化
    handleCurrentChange(PageNum) {
      this.page.pageNum = PageNum
      this.getPageInfo()
    },
    tableRowClassName({rowIndex}) {
      if (rowIndex === 1) {
        return 'warning-row';
      } else if (rowIndex === 3) {
        return 'success-row';
      }
      return '';
    }
  }
}
</script>

<style>
.admin {
  width: 980px;
  float: right;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.cardAdmin {
  width: 300px;
  margin-left: 50%;
  transform: translateX(-50%);
  /*!*height: 350px;*!*/
  /*position: absolute;*/
  /*top: 50%;*/
  /*left: 50%;*/
  /*transform: translate(-50%, -50%);*/
}

.cardAdmin p {
  text-align: center;
  color: #51cacc;
  line-height: 30px;
  margin-bottom: 10px;
  font-weight: 700;
  letter-spacing: 3px;
  margin-top: 15px;
}

.btnAdmin {
  width: 60%;
  height: 40px;
  margin-left: 50% !important;
  transform: translateX(-50%);
  background-image: linear-gradient(
      270deg, rgba(142, 239, 252, .9), rgba(142, 197, 252, .6));
  color: #fff;
  /*margin: 20px 0;*/
}
</style>